package com.zeroup.matrix;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.DeviceUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.bytedance.sdk.open.aweme.CommonConstants;
import com.bytedance.sdk.open.aweme.authorize.model.Authorization;
import com.bytedance.sdk.open.aweme.common.handler.IApiEventHandler;
import com.bytedance.sdk.open.aweme.common.model.BaseReq;
import com.bytedance.sdk.open.aweme.common.model.BaseResp;
import com.bytedance.sdk.open.aweme.share.Share;
import com.cy.cyflowlayoutlibrary.FlowLayout;
import com.cy.cyflowlayoutlibrary.FlowLayoutAdapter;
import com.cy.cyflowlayoutlibrary.FlowLayoutScrollView;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.zeroup.matrix.adapter.VediosAdapter;
import com.zeroup.matrix.appplication.ZeroneAppliction;
import com.zeroup.matrix.bean.AjaxResult;
import com.zeroup.matrix.bean.LoginVo;
import com.zeroup.matrix.bean.MGanVideo;
import com.zeroup.matrix.bean.UserInfo;
import com.zeroup.matrix.download.AndroidDownloadManager;
import com.zeroup.matrix.download.AndroidDownloadManagerListener;
import com.zeroup.matrix.download.AutoVedioDownLoad;
import com.zeroup.matrix.download.ShareVedioDownLoad;
import com.zeroup.matrix.download.VedioDownLoad;
import com.zeroup.matrix.utile.DouyinUtiles;
import com.zeroup.matrix.utile.FileUtils;
import com.zeroup.matrix.utile.PreferencesManager;
import com.zeroup.matrix.utile.SQLiteHelper;
import com.zeroup.matrix.utile.SaveUtils;

import org.kymjs.kjframe.KJActivity;
import org.kymjs.kjframe.KJDB;
import org.kymjs.kjframe.KJHttp;
import org.kymjs.kjframe.http.HttpCallBack;
import org.kymjs.kjframe.http.HttpParams;
import org.kymjs.kjframe.ui.BindView;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.KJLoger;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class VediosActivity extends BaseActivity implements IApiEventHandler {


    @BindView(id=R.id.fl)
    FlowLayoutScrollView flowLayout;

    @BindView(id=R.id.refreshLayout)
    SmartRefreshLayout smartRefreshLayout;

    @BindView(id=R.id.downloadVideo,click = true)
    Button downloadVideo;

    @BindView(id=R.id.shareVideo,click = true)
    Button shareVideo;
    @BindView(id=R.id.logoOut,click = true)
    Button logoOut;

    List<MGanVideo> data = new ArrayList<>();

    private int pageNo=1;

//    private String token;

    private VediosAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String token = getToken();
        if(StringUtils.isEmpty(token)){
            toLogin(this);
            finish();
        }
        this.viewInit();
    }

    private void viewInit(){
        adapter = new VediosAdapter(this,data);
        //5、将适配器加载到控件中
        flowLayout.setAdapter(adapter);

        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                loadData(true,refreshlayout);
//                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
            }
        });
        smartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                loadData(false,refreshlayout);
//                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });
        this.loadData(true,smartRefreshLayout);
    }

    @Override
    public void setRootView() {
        setContentView(R.layout.activity_vedios);
    }


    /**
     * 加载数据
     * @param isRef  是否是刷新
     */
    private void loadData(boolean isRef,RefreshLayout refreshlayout){
        KJHttp kjh = new KJHttp();
        HttpParams params = new HttpParams();
        if(isRef){
            params.put("pageNo",1);
        }else{
            pageNo=pageNo+1;
            params.put("pageNo",pageNo);
        }

        params.put("pageSize",20);
        params.put("sbh",DeviceUtils.getUniqueDeviceId());
        params.putHeaders("X-Access-Token",getToken());
        kjh.get(ZeroneAppliction.apiUrl + "video/mGanVideo/queryPageList" ,params, new HttpCallBack() {
            @Override
            public void onLoading(long count, long current) {
                super.onLoading(count, current);
            }

            @Override
            public void onPreStart() {
            }

            @Override
            public void onSuccess(String o) {
                AjaxResult ajaxResult = JSON.parseObject(o, AjaxResult.class);
                if(ajaxResult.isSuccess()){
                    if(isRef){
                        data.clear();
                        refreshlayout.finishRefresh(true);
                    }else{
                        refreshlayout.finishLoadMore(true);
                    }
                    JSONArray a = (JSONArray)ajaxResult.getResult();
                    if(!a.isEmpty()){
                        data.addAll(a.toJavaList(MGanVideo.class));
                        adapter.notifyDataSetChanged();
                    }else{
                        refreshlayout.setEnableLoadMore(false);
                    }

                }else{
                    Toast.makeText(VediosActivity.this, ajaxResult.getMessage(), Toast.LENGTH_SHORT).show();
                    if(isRef){
                        refreshlayout.finishRefresh(false);
                    }else{
                        refreshlayout.finishLoadMore(false);
                    }
                }

            }

            @Override
            public void onFailure( int errorNo, String strMsg) {
                Toast.makeText(VediosActivity.this, strMsg, Toast.LENGTH_SHORT).show();
                if(isRef){
                    refreshlayout.finishRefresh(false);
                }else{
                    refreshlayout.finishLoadMore(false);
                }
            }
            @Override
            public void onFinish() {

            }
        });
    }

    @Override
    public void widgetClick(View v) {
        super.widgetClick(v);
        switch (v.getId()) {
            case R.id.downloadVideo:
                AutoVedioDownLoad autoVedioDownLoad = new AutoVedioDownLoad(this);
                occupy(autoVedioDownLoad);
                break;
            case R.id.shareVideo:
                ShareVedioDownLoad shareVedioDownLoad = new ShareVedioDownLoad(this);
                occupy(shareVedioDownLoad);
                break;
            case R.id.logoOut:
                logOut();
                break;
        }
    }

    public String getAlbumDirectory() {
        return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).toString();
    }

    private void logOut(){
        Dialog alertDialog = new AlertDialog.Builder(this).
                setTitle("确定退出？").
                setMessage("退出后，会删除绑定关系，确认？").
                setIcon(R.drawable.logo).
                setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        serverLogout();
                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.dismiss();
                    }
                }).create();
        alertDialog.show();
    }

    private void serverLogout(){
        ProgressDialog dialog = new ProgressDialog(this);
        dialog.setMessage("登出中...");
        dialog.setIndeterminate(true);
        dialog.setCancelable(false);
        KJHttp kjh = new KJHttp();
        HttpParams params = new HttpParams();
        params.put("sbh",DeviceUtils.getUniqueDeviceId());
        params.putHeaders("X-Access-Token",getToken());
        kjh.get(ZeroneAppliction.apiUrl + "third/thirdUserInfo/logOut",params, new HttpCallBack() {
            @Override
            public void onLoading(long count, long current) {
                super.onLoading(count, current);
            }

            @Override
            public void onPreStart() {
                dialog.show();
            }

            @Override
            public void onSuccess(String o) {
                AjaxResult ajaxResult = JSON.parseObject(o, AjaxResult.class);
                if(ajaxResult.isSuccess()){
                    KJDB db = KJDB.create(VediosActivity.this);
                    db.deleteByWhere(UserInfo.class,"1=1");
                    Toast.makeText(VediosActivity.this,"即将退出", Toast.LENGTH_SHORT).show();
                    finish();
                }else{
                    Toast.makeText(VediosActivity.this, ajaxResult.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure( int errorNo, String strMsg) {
                Toast.makeText(VediosActivity.this, strMsg, Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onFinish() {
                dialog.dismiss();
            }
        });
    }


    /**
     * 保存视频到相册 完成后调用
     * @param mGanVideo
     */
    public void autoVedioDownloadComd(MGanVideo mGanVideo) {
        SQLiteHelper sqLiteHelper = new SQLiteHelper(getApplicationContext());
        sqLiteHelper.saveOrUpdate(JSON.toJSONString(mGanVideo));
        loadData(true,smartRefreshLayout);
        pushSuccess(mGanVideo.getGid());
    }


    private void occupy(VedioDownLoad vedioDownLoad){
        ProgressDialog dialog = new ProgressDialog(this);
        dialog.setMessage("下载中,请稍等...");
        dialog.setIndeterminate(true);
        dialog.setCancelable(false);
        KJHttp kjh = new KJHttp();
        HttpParams params = new HttpParams();
        String sbh = DeviceUtils.getUniqueDeviceId();
        Log.i("===sbh=={}",sbh);
        params.put("sbh",sbh);
        params.putHeaders("X-Access-Token",getToken());
        kjh.get(ZeroneAppliction.apiUrl + "video/mGanVideo/occupy",params, new HttpCallBack() {
            @Override
            public void onLoading(long count, long current) {
                super.onLoading(count, current);
            }

            @Override
            public void onPreStart() {
                dialog.show();
            }

            @Override
            public void onSuccess(String o) {
                AjaxResult ajaxResult = JSON.parseObject(o, AjaxResult.class);
                if(ajaxResult.isSuccess()){
                    JSONObject re = (JSONObject) ajaxResult.getResult();
                    MGanVideo mGanVideo = re.toJavaObject(MGanVideo.class);
                    vedioDownLoad.download(mGanVideo);
                }else{
                    Toast.makeText(VediosActivity.this, ajaxResult.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure( int errorNo, String strMsg) {
                Toast.makeText(VediosActivity.this, strMsg, Toast.LENGTH_SHORT).show();
            }
            @Override
            public void onFinish() {
                dialog.dismiss();
            }
        });
    }

    private void pushSuccess(String gid){
        KJHttp kjh = new KJHttp();
        HttpParams params = new HttpParams();
        Log.i("===gid=={}",gid);
        params.put("gid",gid);
        params.putHeaders("X-Access-Token",getToken());
        kjh.get(ZeroneAppliction.apiUrl + "video/mGanVideo/pushSuccess",params, new HttpCallBack() {
            @Override
            public void onLoading(long count, long current) {
                super.onLoading(count, current);
            }

            @Override
            public void onPreStart() {
            }

            @Override
            public void onSuccess(String o) {
                AjaxResult ajaxResult = JSON.parseObject(o, AjaxResult.class);
                if(ajaxResult.isSuccess()){
                    Log.i("pushSuccess:{}","success");
                }else{
                    Log.i("pushSuccess:{}",ajaxResult.getMessage());
                }
            }

            @Override
            public void onFailure( int errorNo, String strMsg) {
               Log.i("pushSuccess:{}",strMsg);
            }
            @Override
            public void onFinish() {

            }
        });
    }

    @Override
    public void onReq(BaseReq baseReq) {
        Log.d("onReq===>{}",baseReq.toString()+"");
    }

    @Override
    public void onResp(BaseResp resp) {
        Log.d("onResp===>{}",resp.errorCode+"");
        // 授权成功可以获得authCode
        if (resp.getType() == CommonConstants.ModeType.SHARE_CONTENT_TO_TT_RESP) {
            Share.Response response = (Share.Response) resp;
            if(response.isSuccess()){
                this.pushSuccess(response.state);
            }else{
                // 错误码除了response.errorCode字段，还增加了response.subErrorCode字段，帮助三方排查错误原因
                LogUtils.eTag("onResp===>{}", "分享失败,errorCode: " + response.errorCode + "subcode" + response.subErrorCode + " Error Msg : " +
                        response.errorMsg);
            }

        }else {
            Log.e("onResp===>{}",resp.errorMsg);
        }
    }

    @Override
    public void onErrorIntent(Intent intent) {
        Log.e("onErrorIntent===>{}", "Intent出错");
    }
}